package com.gobang.modules.record;

import com.gobang.entity.GameRecord;
import com.gobang.modules.room.Room;
import com.gobang.mapper.GameRecordMapper;
import com.gobang.proto.GameProto.GameResult;
import com.gobang.modules.login.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class GameRecordService {
    
    @Autowired
    private GameRecordMapper gameRecordMapper;
    @Autowired
    private UserService userService;
    
    /**
     * 保存游戏记录
     */
    public void saveGameRecord(Room room) {
        GameRecord record = new GameRecord();
        record.setGameId(room.getGameId());
        record.setBlackPlayerId(room.getBlackPlayerId());
        record.setWhitePlayerId(room.getWhitePlayerId());
        record.setWinnerId(room.getWinnerId());
        record.setResult(room.getResult().getNumber());
        record.setTotalMoves(room.getMoveCount());
        record.setStartTime(room.getStartTime());
        record.setEndTime(LocalDateTime.now());
        record.setCreateTime(LocalDateTime.now());
        
        gameRecordMapper.insert(record);
        
        // 更新玩家战绩
        updatePlayerStats(room);
    }
    
    /**
     * 更新玩家战绩
     */
    private void updatePlayerStats(Room room) {
        GameResult result = room.getResult();
        Long blackPlayerId = room.getBlackPlayerId();
        Long whitePlayerId = room.getWhitePlayerId();
        
        if (result == GameResult.BLACK_WIN) {
            userService.updateUserStats(blackPlayerId, true, false);
            userService.updateUserStats(whitePlayerId, false, false);
        } else if (result == GameResult.WHITE_WIN) {
            userService.updateUserStats(whitePlayerId, true, false);
            userService.updateUserStats(blackPlayerId, false, false);
        } else if (result == GameResult.DRAW) {
            userService.updateUserStats(blackPlayerId, false, true);
            userService.updateUserStats(whitePlayerId, false, true);
        } else if (result == GameResult.SURRENDER_RESULT) {
            // 投降方判负
            Long winnerId = room.getWinnerId();
            Long loserId = winnerId.equals(blackPlayerId) ? whitePlayerId : blackPlayerId;
            userService.updateUserStats(winnerId, true, false);
            userService.updateUserStats(loserId, false, false);
        }
    }
}
